package com.dianneng.show.fragment;


import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.Utils;
import com.dianneng.show.R;
import com.dianneng.show.base.BaseFragment;
import com.dianneng.show.http.RetrofitHelper;
import com.dianneng.show.model.MonthInfo;
import com.dianneng.show.util.ACache;
import com.dianneng.show.util.Constant;
import com.dianneng.show.util.DateUtil;
import com.dianneng.show.widget.DayValueFormatter;
import com.dianneng.show.widget.XY2MarkerView;
import com.dianneng.show.widget.YValueFormatter;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.xingliuhua.libnetstatelayout.view.INetErrorView;
import com.xingliuhua.libnetstatelayout.view.NetStateLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class CompareFragment extends BaseFragment {

    @BindView(R.id.lc_dianliang)
    LineChart lcDianliang;
    @BindView(R.id.tv_time1)
    TextView tvTime1;
    @BindView(R.id.tv_time2)
    TextView tvTime2;
    @BindView(R.id.nt_total)
    NetStateLayout ntTotal;
    @BindView(R.id.sw_content)
    SwipeRefreshLayout swContent;

    private DateUtil.DateInfo dateInfo1, dateInfo2;

    @Override
    protected int setLayoutResourceID() {
        return R.layout.fragment_compare;
    }

    @Override
    protected void setUpView() {
        initLineChart();
        swContent.setColorSchemeResources(R.color.colorPrimaryDark, R.color.colorPrimary, R.color.colorAccent);
        swContent.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                swContent.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        setUpData();
                    }
                }, 1000);
            }
        });
        ntTotal.setContentState(NetStateLayout.CONTENT_STATE_SHOW_LOADING);
        ntTotal.setOnRetryClickListener(new INetErrorView.OnRetryClickListener() {
            @Override
            public void onRetryClicked() {
                ntTotal.setContentState(NetStateLayout.CONTENT_STATE_SHOW_LOADING);
                setUpData();
            }
        });

        dateInfo1 = DateUtil.getCurrentDate();
        dateInfo2 = DateUtil.getPreDate(dateInfo1);

        tvTime1.setText(dateInfo1.getYear()+"年"+dateInfo1.getMonth()+"月");
        tvTime2.setText(dateInfo2.getYear()+"年"+dateInfo2.getMonth()+"月");
        xyMarkerView.setDateInfo1(dateInfo1);
        xyMarkerView.setDateInfo2(dateInfo2);
    }

    @Override
    protected void setUpData() {
        getMonthData1();
    }

    XY2MarkerView xyMarkerView;
    /**
     * 初始化折线图控件属性
     */
    private void initLineChart() {
        lcDianliang.getDescription().setEnabled(false);
        lcDianliang.setDoubleTapToZoomEnabled(false);
        lcDianliang.setScaleEnabled(false);
        lcDianliang.setBackgroundColor(getResources().getColor(R.color.white));
        lcDianliang.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {
            @Override
            public void onValueSelected(Entry e, Highlight h) {
                lcDianliang.getXAxis().removeAllLimitLines();
                LimitLine xLimitLine = new LimitLine(e.getX(), "");
                xLimitLine.setLineColor(getResources().getColor(R.color.gray_2));
                xLimitLine.setTextColor(getResources().getColor(R.color.gray_2));
                lcDianliang.getXAxis().addLimitLine(xLimitLine);
            }

            @Override
            public void onNothingSelected() {
                lcDianliang.getXAxis().removeAllLimitLines();
            }
        });

        ValueFormatter dayValueFormatter = new DayValueFormatter();
        XAxis xAxis = lcDianliang.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setGranularity(1f);
        xAxis.setDrawGridLines(false);
        xAxis.setLabelCount(25, false);
        xAxis.setValueFormatter(dayValueFormatter);


        ValueFormatter yValueFormatter = new YValueFormatter();
        YAxis leftAxis = lcDianliang.getAxisLeft();
        leftAxis.setLabelCount(8, false);
        leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
        leftAxis.setSpaceTop(16f);
        leftAxis.setAxisMinimum(0f);
        leftAxis.setValueFormatter(yValueFormatter);

        lcDianliang.getAxisRight().setEnabled(false);

        xyMarkerView = new XY2MarkerView(getActivity());
        xyMarkerView.setChartView(lcDianliang);
        lcDianliang.setMarker(xyMarkerView);
    }

    /**
     * 设置折线图的数据
     */
    private void setLineChartData() {
        lcDianliang.getXAxis().removeAllLimitLines();
        lcDianliang.clear();

        //填充数据，在这里换成自己的数据源
        List<Entry> valsComp1 = new ArrayList<>();
        List<Entry> valsComp2 = new ArrayList<>();

        for (int i = 1; i < 32; i++) {
            valsComp1.add(new Entry(i, monthDatas1.get(i-1).getEq()));
            valsComp2.add(new Entry(i, monthDatas2.get(i-1).getEq()));
        }

        //这里，每重新new一个LineDataSet，相当于重新画一组折线
        //每一个LineDataSet相当于一组折线。比如:这里有两个LineDataSet：setComp1，setComp2。
        //则在图像上会有两条折线图，分别表示公司1 和 公司2 的情况.还可以设置更多
        LineDataSet setComp1 = new LineDataSet(valsComp1, dateInfo1.getYear()+"年"+dateInfo1.getMonth()+"月");
        setComp1.setAxisDependency(YAxis.AxisDependency.LEFT);
        setComp1.setColor(getResources().getColor(R.color.colorPrimary));
        setComp1.setDrawCircles(true);
        setComp1.setCircleColor(getResources().getColor(R.color.colorPrimary));
        setComp1.setMode(LineDataSet.Mode.LINEAR);
        setComp1.setDrawFilled(true);
        setComp1.setFillColor(getResources().getColor(R.color.colorPrimary));
        setComp1.setDrawCircleHole(true);
        setComp1.setCircleHoleColor(getResources().getColor(R.color.colorPrimary));
        setComp1.setHighLightColor(getResources().getColor(R.color.tra)); // 设置点击某个点时，横竖两条线的颜色
        setComp1.setValueTextColor(getResources().getColor(R.color.colorPrimary));
        setComp1.setValueTextSize(10f);

        LineDataSet setComp2 = new LineDataSet(valsComp2, dateInfo2.getYear()+"年"+dateInfo2.getMonth()+"月");
        setComp2.setAxisDependency(YAxis.AxisDependency.LEFT);
        setComp2.setColor(getResources().getColor(R.color.colorAccent));
        setComp2.setDrawCircles(true);
        setComp2.setCircleColor(getResources().getColor(R.color.colorAccent));
        setComp2.setMode(LineDataSet.Mode.LINEAR);
        setComp2.setDrawFilled(true);
        setComp2.setFillColor(getResources().getColor(R.color.colorAccent));
        setComp2.setDrawCircleHole(true);
        setComp2.setCircleHoleColor(getResources().getColor(R.color.colorAccent));
        setComp2.setHighLightColor(getResources().getColor(R.color.tra)); // 设置点击某个点时，横竖两条线的颜色
        setComp2.setValueTextColor(getResources().getColor(R.color.colorAccent));
        setComp2.setValueTextSize(10f);

        List<ILineDataSet> dataSets = new ArrayList<>();
        dataSets.add(setComp1);
        dataSets.add(setComp2);

        LineData lineData = new LineData(dataSets);
        lineData.setDrawValues(false);
        lineData.setHighlightEnabled(true);

        lcDianliang.setData(lineData);
        lcDianliang.highlightValue(valsComp1.get(valsComp1.size()-1).getX(),0);
        lcDianliang.invalidate();
    }

    @OnClick({R.id.iv_left1, R.id.iv_right1, R.id.iv_left2, R.id.iv_right2})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_left1:
                DateUtil.DateInfo tmp1=DateUtil.getPreDate(dateInfo1);
                if (!dateInfo1.equals(tmp1) && !dateInfo2.equals(tmp1)){
                    dateInfo1=tmp1;
                    tvTime1.setText(dateInfo1.getYear()+"年"+dateInfo1.getMonth()+"月");
                    getMonthData1();
                    break;
                }
                 tmp1=DateUtil.getPreDate(tmp1);
                if (!dateInfo1.equals(tmp1) && !dateInfo2.equals(tmp1)){
                    dateInfo1=tmp1;
                    tvTime1.setText(dateInfo1.getYear()+"年"+dateInfo1.getMonth()+"月");
                    getMonthData1();
                    break;
                }
                break;
            case R.id.iv_right1:
                DateUtil.DateInfo tmp2=DateUtil.getNextDate(dateInfo1);
                if (!dateInfo1.equals(tmp2) && !dateInfo2.equals(tmp2)){
                    dateInfo1=tmp2;
                    tvTime1.setText(dateInfo1.getYear()+"年"+dateInfo1.getMonth()+"月");
                    getMonthData1();
                    break;
                }
                tmp2=DateUtil.getNextDate(tmp2);
                if (!dateInfo1.equals(tmp2) && !dateInfo2.equals(tmp2)){
                    dateInfo1=tmp2;
                    tvTime1.setText(dateInfo1.getYear()+"年"+dateInfo1.getMonth()+"月");
                    getMonthData1();
                    break;
                }
                break;
            case R.id.iv_left2:
                DateUtil.DateInfo tmp3=DateUtil.getPreDate(dateInfo2);
                if (!dateInfo1.equals(tmp3) && !dateInfo2.equals(tmp3)){
                    dateInfo2=tmp3;
                    tvTime2.setText(dateInfo2.getYear()+"年"+dateInfo2.getMonth()+"月");
                    getMonthData1();
                    break;
                }
                tmp3=DateUtil.getPreDate(tmp3);
                if (!dateInfo1.equals(tmp3) && !dateInfo2.equals(tmp3)){
                    dateInfo2=tmp3;
                    tvTime2.setText(dateInfo2.getYear()+"年"+dateInfo2.getMonth()+"月");
                    getMonthData1();
                    break;
                }
                break;
            case R.id.iv_right2:
                DateUtil.DateInfo tmp4=DateUtil.getNextDate(dateInfo2);
                if (!dateInfo1.equals(tmp4) && !dateInfo2.equals(tmp4)){
                    dateInfo2=tmp4;
                    tvTime2.setText(dateInfo2.getYear()+"年"+dateInfo2.getMonth()+"月");
                    getMonthData1();
                    break;
                }
                tmp4=DateUtil.getNextDate(tmp4);
                if (!dateInfo1.equals(tmp4) && !dateInfo2.equals(tmp4)){
                    dateInfo2=tmp4;
                    tvTime2.setText(dateInfo2.getYear()+"年"+dateInfo2.getMonth()+"月");
                    getMonthData1();
                    break;
                }
                break;
        }
    }

    List<MonthInfo.DataBean> monthDatas1 = new ArrayList<>();
    List<MonthInfo.DataBean> monthBarDatas1 = new ArrayList<>();
    private void getMonthData1() {
        mLoadingDialog.setLoadingText("获取数据中...").show();
        disposables.add(RetrofitHelper.getHelper(getActivity()).getUserInfoService().listmonth(ACache.get(Utils.getApp()).getAsString(Constant.TEMP_SN), dateInfo1.getYear()+"", dateInfo1.getMonth()+"")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<MonthInfo>() {
                    @Override
                    public void accept(MonthInfo info) {
                        monthDatas1.clear();
                        monthDatas1 = MonthInfo.getLineData(info.getData());
                        monthBarDatas1.clear();
                        monthBarDatas1=MonthInfo.getBarData(info.getData());

                        xyMarkerView.setMonthBarDatas1(monthBarDatas1);
                        xyMarkerView.setMonthDatas1(monthDatas1);
                        getMonthData2();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) {
                        throwable.printStackTrace();
                        ntTotal.setContentState(NetStateLayout.CONTENT_STATE_HIDE);
                        ToastUtils.showLong("网络信号质量较差，请稍后刷新重试");
                        mLoadingDialog.close();
                        swContent.setRefreshing(false);
                    }
                })
        );
    }

    List<MonthInfo.DataBean> monthDatas2 = new ArrayList<>();
    List<MonthInfo.DataBean> monthBarDatas2 = new ArrayList<>();
    private void getMonthData2() {
        disposables.add(RetrofitHelper.getHelper(getActivity()).getUserInfoService().listmonth(ACache.get(Utils.getApp()).getAsString(Constant.TEMP_SN), dateInfo2.getYear()+"", dateInfo2.getMonth()+"")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<MonthInfo>() {
                    @Override
                    public void accept(MonthInfo info) {
                        monthDatas2.clear();
                        monthDatas2 = MonthInfo.getLineData(info.getData());
                        monthBarDatas2.clear();
                        monthBarDatas2=MonthInfo.getBarData(info.getData());

                        xyMarkerView.setMonthBarDatas2(monthBarDatas2);
                        xyMarkerView.setMonthDatas2(monthDatas2);

                        xyMarkerView.setDateInfo1(dateInfo1);
                        xyMarkerView.setDateInfo2(dateInfo2);

                        ntTotal.setContentState(NetStateLayout.CONTENT_STATE_HIDE);
                        swContent.setRefreshing(false);
                        mLoadingDialog.close();
                        setLineChartData();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) {
                        throwable.printStackTrace();
                        ntTotal.setContentState(NetStateLayout.CONTENT_STATE_HIDE);
                        ToastUtils.showLong("网络信号质量较差，请稍后刷新重试");
                        mLoadingDialog.close();
                        swContent.setRefreshing(false);
                    }
                })
        );
    }
}
